package conson.tech.manage.activity.service.impl;

import cn.hutool.json.JSONUtil;
import conson.tech.core.exception.BaseException;
import conson.tech.manage.activity.entity.dto.*;
import conson.tech.manage.activity.service.CouPonCallService;
import conson.tech.manage.common.constant.BusinessMessage;
import conson.tech.manage.common.service.RestTemplateClient;
import conson.tech.manage.common.util.EPassSignUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: CouPonCallServiceImpl
 * Description: 优惠券调用服务实现类
 * Author: HXL
 * Date: 2020/5/25 3:37 下午
 * Version: 1.0
 */
@Slf4j
@RefreshScope
@Service
public class CouPonCallServiceImpl implements CouPonCallService {

    private final String CHARSET = "UTF-8";

    private final String VERSION = "1.0";
    private final String TRANSIT_RECHARGE_BUS = "100001";

    @Value("${transit.recharge.activity}")
    private String transitRechargeActivity;

    @Value("${epass.appId}")
    private String appId;

    @Value("${epass.privateKey}")
    private String privateKey;
    @Value("${epass.baseCouponUrl}")
    private String couponPath;

    @Value("${epass.couponUser}")
    private String couponUser;

    @Value("${epass.spring.couponEId}")
    private String couponEId;
    @Value("${epass.spring.couponPId}")
    private String couponPId;
    @Value("${epass.spring.couponCount}")
    private String couponCount;

    //海水
    @Value("${bathbeach.orderUrl}")
    private String bathBeachPath;
    @Value("${bathbeach.skuId}")
    private String beachSkuId;
    @Value("${bathbeach.skuName}")
    private String skuName;
    @Value("${bathbeach.payWay}")
    private String payWay;
    @Value("${bathbeach.buyWay}")
    private String buyWay;
    @Value("${bathbeach.itemId}")
    private String itemId;
    //博物馆
    @Value("${museum.skuId}")
    private String museumSkuId;
    @Value("${museum.orderUrl}")
    private String museumPath;
    @Autowired
    private RestTemplateClient restTemplateClient;

    //    @Autowired
//    private CouponService couponService;
    //隧E通
    @Override
    public String EPassGrantTicket(String mobile) {
        Map<String, String> map = buildCouponRequestParam(mobile, 1);
        log.info("CouPonCallServiceImpl -> EPassGrantTicket 隧E通发送优惠券入参为:[{}]", JSONUtil.toJsonStr(map));
        String str = restTemplateClient.postForEntity(couponPath, map);
        EPassResponse ePassResponse = JSONUtil.toBean(str, EPassResponse.class);
        log.info("CouPonCallServiceImpl -> EPassGrantTicket 隧E通发送优惠券返回的数据为:[{}]", JSONUtil.toJsonStr(ePassResponse));
        if (ePassResponse != null && ePassResponse.getCode().equals("0")) {
            return ePassResponse.getData().getItemIds();
        } else {
            throw new BaseException(BusinessMessage.E_PASS_ERROR);
        }
    }

    //二维码充值优惠
    /*@Override
    public String transitRechargeGrantTicket(CouponFeginForm feginForm) {
        feginForm.setBusinessCode(TRANSIT_RECHARGE_BUS);
        feginForm.setActiveNo(transitRechargeActivity);
        feginForm.setSurplusAmount("0");
        feginForm.setBusinessStandard("0");
        log.info("CouPonCallServiceImpl -> transitRechargeGrantTicket 二维码充值发送优惠券入参为:[{}]",JSONUtil.toJsonStr(feginForm));
        Response<CouponFeginVo> couponFeginVoResponse = couponService.applyCoupon(feginForm);
        log.info("CouPonCallServiceImpl -> transitRechargeGrantTicket 二维码充值发送优惠券返回的数据为:[{}]",JSONUtil.toJsonStr(couponFeginVoResponse));
        if (couponFeginVoResponse != null && couponFeginVoResponse.getCode() == 200){
            CouponFeginVo result = couponFeginVoResponse.getResult();
                return result.getCouponIndentify();
        }else {
            throw new BaseException(BusinessMessage.GJ_COUPON_ERROR);
        }
    }*/
    //停车场
    @Override
    public String ParkingLotTicket(String mobile) {
        Map<String, String> map = buildCouponRequestParam(mobile, 2);
        log.info("CouPonCallServiceImpl -> ParkingLotTicket 停车场发送优惠券入参为:[{}]", JSONUtil.toJsonStr(map));
        String str = restTemplateClient.postForEntity(couponPath, map);
        EPassResponse ePassResponse = JSONUtil.toBean(str, EPassResponse.class);
        log.info("CouPonCallServiceImpl -> EPassGrantTicket 停车场发送优惠券返回的数据为:[{}]", JSONUtil.toJsonStr(ePassResponse));
        if (ePassResponse != null && ePassResponse.getCode().equals("0")) {
            return ePassResponse.getData().getItemIds();
        } else {
            throw new BaseException(BusinessMessage.TCC_COUPON_ERROR);
        }
    }

    //激活海水浴场
    @Override
    public String activationBathBeachTicket(BathBeachTicketDTO dto) {
        List<BathBeachTicketListDTO> createTicketList = dto.getCreateTicketList();
        createTicketList.stream().forEach(bathBeachTicket -> {
            bathBeachTicket.setSkuId(beachSkuId);
            bathBeachTicket.setSkuName(skuName);
            bathBeachTicket.setItemId(itemId);
        });
        dto.setBuyWay(buyWay);
        dto.setPayWay(payWay);
        log.info("CouPonCallServiceImpl -> activationBathBeachTicket 激活海水浴场更衣票入参为:[{}]", JSONUtil.toJsonStr(dto));
        String str = restTemplateClient.postForEntityJSON(bathBeachPath, JSONUtil.toJsonStr(dto));
        TourismResponse response = JSONUtil.toBean(str, TourismResponse.class);
        log.info("CouPonCallServiceImpl -> activationBathBeachTicket 激活海水浴场更衣票返回的数据为:[{}]", JSONUtil.toJsonStr(response));
        if (response != null && response.getCode() == 200) {
            return (String) response.getResult();
        } else {
            throw new BaseException(BusinessMessage.HSYC_COUPON_ERROR);
        }
    }

    //博物馆
    @Override
    public String museumTicket(Long userId, String mobile, Date ticketStartTime, Date ticketEndTime) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MuseumTicketOrderDTO dto = new MuseumTicketOrderDTO();
        dto.setGoodsId(museumSkuId);
        dto.setMobile(mobile);
        dto.setUid(userId);
        dto.setTicketNumber(1);
        dto.setWriteOffStartTime(sf.format(ticketStartTime));
        dto.setWriteOffEndTime(sf.format(ticketEndTime));
        log.info("CouPonCallServiceImpl -> museumTicket 博物馆免费票发放入参为:[{}]", JSONUtil.toJsonStr(dto));
        String str = restTemplateClient.postForEntityJSON(museumPath, JSONUtil.toJsonStr(dto));
        TourismResponse response = JSONUtil.toBean(str, TourismResponse.class);
        log.info("CouPonCallServiceImpl -> museumTicket 博物馆免费票发放返回的数据为:[{}]", JSONUtil.toJsonStr(response));
        if (response != null && response.getCode() == 200) {
            OrderNumberStrDTO orderNumberStrDTO = JSONUtil.toBean(JSONUtil.toJsonStr(response.getResult()), OrderNumberStrDTO.class);
            return orderNumberStrDTO.getOrderId();
        } else {
            throw new BaseException(BusinessMessage.BWJ_COUPON_ERROR);
        }
    }

    private Map<String, String> buildCouponRequestParam(String mobile, int type) {

        Map<String, String> reqMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        reqMap.put("timestamp", sdf.format(new Date()));
        reqMap.put("appId", appId);
        reqMap.put("charset", CHARSET);
        reqMap.put("version", VERSION);
        reqMap.put("userName", couponUser);
        if (type == 1) {
            reqMap.put("coupon_id", couponEId);//
        } else if (type == 2) {
            reqMap.put("coupon_id", couponPId);//
        }
        reqMap.put("phone_no", mobile);
        reqMap.put("put_count", couponCount);
        reqMap.put("sign", this.getSign(EPassSignUtils.createPlainText(reqMap)));
        return reqMap;
    }

    private String getSign(String reqParam) {
        PrivateKey key = EPassSignUtils.restorePrivateKey(privateKey);
        return EPassSignUtils.sign(key, reqParam);
    }
}
